import { useEffect, useRef, useState } from 'react'
import { Button, message, Radio, RadioChangeEvent, Spin } from 'antd'
import './index.less'
import QsfLogin from './components/qsfLogin'
import GYSLogin from './components/gYSLogin'
import OauthLoginIcon from './components/oauthList'
import DDLogin from './components/ddLogin'
import SliderVerify from '@/components/SliderVerify'
import { useForm } from 'antd/es/form/Form'
import { getUserButton, userLogin, userLoginByDDQrcode } from '@/api/system'
import { updateUserPassword } from '@/api/user'
import { applicationTypeEnum, orgTypeEnum } from '@/constant'
import FirstLoginChangePasswordModal from './components/firstLogin'
import {
  changeRouteList,
  changeMenuList,
  changeUserRouteList,
  changeDictData,
  changeButtonCodeList,
} from '@/store/reducers/login'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
import { changeUserInfoAction } from '@/store/reducers/user'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { getAllRouteTree, getAllMenuTree, getUserRouteTree } from '@/api/role'
import { getAllDictData } from '@/api/dict'
import { Cache_Key, Token_Key } from '@/config'
import qsfLogo from '@/assets/images/logo.png'
import { deepFilterChild } from '@/router/routerBefore'
export interface IUserInfo {
  id?: string
  phoneNumber?: string
  userId?: string
  userName?: string
  workId?: string
  applicationId?: string
}
const Index = () => {
  const dispatch = useAppDispatch()
  const [oauthType, setoauthType] = useState('')
  const [loginType, setLoginType] = useState<orgTypeEnum.SEVENFUN | orgTypeEnum.SUPPLIER>(orgTypeEnum.SEVENFUN)
  const [sliderSuccess, setSliderSuccess] = useState<boolean>(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [loading, setLoading] = useState<boolean>(false)
  const authCode = new URLSearchParams(window.location.search).get('authCode')
  const sliderRef = useRef<InstanceType<typeof SliderVerify>>(null)
  const [firstLoginModal, setFirstLoginModal] = useState<boolean>(false)
  const [form] = useForm()
  const [changePasswordForm] = useForm()
  const userInfo = useRef<IUserInfo>()
  const navigate = useNavigate()
  const [query] = useSearchParams()
  const redirectUrl = query.get('redirectUrl') || (authCode ? '' : decodeURIComponent(location?.search).slice(1))
  const token = window.localStorage.getItem(Token_Key)
  const userMenu = useAppSelector((state) => state.login.userRouteList)
  useEffect(() => {
    if (authCode) {
      setLoading(true)
      DDQrcodeLogin()
      return
    }
    if (token && userMenu && userMenu.length) {
      if (redirectUrl) {
        navigate(redirectUrl)
        return
      }
      const item = userMenu[0]
      if (item.children && item.children.length > 0) {
        navigate(item.children[0].fullPath)
      } else {
        navigate(item.fullPath)
      }
      return
    }
  }, [])
  const handleSetLoginType = (event: RadioChangeEvent) => {
    setispedding(false)
    setLoginType(event.target.value)
    form.resetFields()
    setSliderSuccess(false)
    sliderRef.current?.reset()
  }
  const onFinish = async () => {
    try {
      const data = await form.validateFields()
      if (!sliderSuccess) {
        message.warning('请进行滑动验证')
        return
      }
      setispedding(true)
      const applicationId =
        loginType === 0 ? applicationTypeEnum.SOP_SEVENFUN_WEB : applicationTypeEnum.SOP_SUPPLIER_WEB
      const res = await userLogin({
        applicationId,
        orgType: loginType,
        orgCode: loginType === 0 ? 'QSF' : '',
        ...data,
      })
      if (res.code === 200) {
        window.localStorage.setItem(Token_Key, res.data.accessToken)
        dispatch(changeUserInfoAction({ ...res.data.userDTO, applicationId }))
        userInfo.current = { ...res.data.userDTO, applicationId }
        if (res.data.firstLogin === 1) {
          setFirstLoginModal(true)
          setispedding(false)
          return
        }
        await onLoginSuccess()
      }
    } catch (error) {
      setispedding(false)
    }
  }
  const DDQrcodeLogin = async () => {
    try {
      const applicationId = applicationTypeEnum.SOP_SEVENFUN_WEB
      const res = await userLoginByDDQrcode({ authCode, applicationId })
      if (res.code === 200) {
        window.localStorage.setItem(Token_Key, res.data.accessToken)
        dispatch(changeUserInfoAction({ ...res.data.userDTO, applicationId }))
        userInfo.current = { ...res.data.userDTO, applicationId }
        if (res.data.firstLogin === 1) {
          setFirstLoginModal(true)
          return
        }
        await onLoginSuccess()
      }
    } catch (error) {
      setLoading(false)
    }
  }
  const onSliderSuccess = () => {
    setSliderSuccess(true)
  }
  const onChangePasswordFinish = async () => {
    try {
      const formdata = await changePasswordForm.validateFields()
      setispedding(true)
      const res = await updateUserPassword({ id: userInfo?.current?.userId, password: formdata.newpassword })
      if (res.code === 200) {
        await onLoginSuccess()
      }
    } catch (error) {
      setispedding(false)
    }
  }
  const getRoutesAndMenu = async () => {
    const routes = await getAllRouteTree<IRoutesType>({ applicationId: userInfo?.current?.applicationId })
    dispatch(changeRouteList(routes.data))
    const menu = await getAllMenuTree<IRoutesType>({
      userId: userInfo?.current?.userId,
      applicationId: userInfo?.current?.applicationId,
    })
    dispatch(changeMenuList(menu.data))
    const user_routes = await getUserRouteTree<IRoutesType>({
      userId: userInfo?.current?.userId,
      applicationId: userInfo?.current?.applicationId,
    })
    dispatch(changeUserRouteList(user_routes.data))
    const buttonCodeList = await getUserButton<string[]>({
      userId: userInfo?.current?.userId,
      applicationId: userInfo?.current?.applicationId,
    })
    dispatch(changeButtonCodeList(buttonCodeList.data))
    console.log([menu, user_routes], '[menu, user_routes]')
    return [menu, user_routes]
  }
  const onLoginSuccess = async () => {
    window.sessionStorage.removeItem(Cache_Key)
    const [menu, user_routes] = await getRoutesAndMenu().finally(() => setispedding(false))
    if (menu.data && menu.data.length > 0 && user_routes.data && user_routes.data.length > 0) {
      getDict()
      if (redirectUrl) {
        const regex = /^\/(?:[^/?]+\/){2}[^/?]+\/?/
        const url = redirectUrl.match(regex)?.[0]
        if (url) {
          const result = deepFilterChild(user_routes?.data || [], url)
          if (result && result.length > 0) {
            navigate(redirectUrl)
            message.success('欢迎登录')
            return
          }
        }
      }
      const item = menu.data[0]
      if (item.children && item.children.length > 0) {
        navigate(item.children[0].fullPath)
      } else {
        navigate(item.fullPath)
      }
      message.success('欢迎登录')
    } else {
      message.warning('您没有访问该系统的权限，请联系管理员进行配置！')
      setFirstLoginModal(false)
      setLoading(false)
      return
    }
  }
  const getDict = async () => {
    const dict = await getAllDictData<Record<string, IOptionItem[]>>({ status: 1 })
    if (dict.code === 200) {
      dispatch(changeDictData(dict.data))
    }
  }
  return (
    <div className="login_page_wrap">
      <div className="login_image_box"></div>
      <div className="login_info_wrap">
        <div className="flip-card login_info_box">
          <div className="flip-card-inner">
            <div className={'flip-card-front' + (oauthType ? ' show_card' : ' hidden_card')}>
              <div className="login_info_box">
                <div className="login_info_content">
                  <div className="login_info_logo">
                    <img src={qsfLogo} alt="" />
                  </div>
                  <div className="login_info_title">七色纺产供销一体化平台</div>
                  <div className="login_tabs_wrap">
                    <Radio.Group defaultValue={orgTypeEnum.SEVENFUN} onChange={handleSetLoginType}>
                      <Radio.Button value={orgTypeEnum.SEVENFUN} style={{ flex: 1, textAlign: 'center' }}>
                        七色纺登录
                      </Radio.Button>
                      <Radio.Button value={orgTypeEnum.SUPPLIER} style={{ flex: 1, textAlign: 'center' }}>
                        供应商登录
                      </Radio.Button>
                    </Radio.Group>
                  </div>
                  <div className="login_func_box">
                    {loginType === orgTypeEnum.SEVENFUN ? (
                      <QsfLogin form={form}></QsfLogin>
                    ) : (
                      <GYSLogin form={form}></GYSLogin>
                    )}
                    <SliderVerify onSuccess={onSliderSuccess} ref={sliderRef}></SliderVerify>
                    <Button block type="primary" onClick={onFinish} loading={ispedding}>
                      登录
                    </Button>
                  </div>
                  {loginType === orgTypeEnum.SEVENFUN && (
                    <div className="login_oauth2_box">
                      <div className="login_oauth2_title">其它登录方式</div>
                      <OauthLoginIcon onClick={(val: string) => setoauthType(val)}></OauthLoginIcon>
                    </div>
                  )}
                </div>
              </div>
            </div>
            <div className={'flip-card-back' + (!oauthType ? ' show_card' : ' hidden_card')}>
              {oauthType && <DDLogin onClick={() => setoauthType('')}></DDLogin>}
            </div>
          </div>
        </div>
      </div>
      <div className="coryright_wrap">Copyright © 2024-2025 七色纺商业连锁有限公司 版权所有</div>
      <FirstLoginChangePasswordModal
        loading={ispedding}
        form={changePasswordForm}
        onFinish={onChangePasswordFinish}
        open={firstLoginModal}
      ></FirstLoginChangePasswordModal>
      <Spin spinning={loading} indicator={<div id="page_loading_login"></div>} fullscreen />
    </div>
  )
}

export default Index
